#-*-coding: utf-8-*-
import socket
import sys
print("""
###########################################################
# PortScan codado por felipe silva                        #
###########################################################
""")
# função testa conexão reversa para testar se tem firewall
def testeMac():
  if sys.argv[1] == "tcp":
      print("Testando conexão reversa...")
      soquet.send("0".encode("utf-8"))
      x = soquet.recv(1024)
      if len(x.decode("utf-8")) < 1:
        print("Porta {} filtrada!".format(sys.argv[3]))
      else:
        print("Porta {} não filtrada!".format(sys.argv[3]))
  elif sys.argv[1] == "udp":
      print("Testando conexão reversa...")
      x = soquet.recv(1024)
      print("Porta {} não filtrada!".format(sys.argv[3]))
  else:
    erro()
    # função de erro
def erro():
  print("Deu pau ae mano!\nVocê passou os parametros corretos?")
  print("Exemplo de uso:\nPortScan.py tcp 192.168.0.1 80")
  print("PortScan.py [1 protcolo] [2 ip] [3 porta]")
# argv[1] pega protocolo
# no caso argv[2] pega ip
# argv[3] pega porta
try:
  proto = str(sys.argv[1])
  ip = str(sys.argv[2])
  port = int(sys.argv[3])
  addr = ((ip, port))
  if proto == "tcp":
    # testa portas tcp
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as soquet:
      ValorConx = soquet.connect_ex(addr)
      if ValorConx == 0:
        print("Porta {} aberta disponivel".format(sys.argv[3]))
        testeMac()
      else:
        print("Porta fechada")
        # testa portas udp
  elif proto == "udp":
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as soquet:
      ValorConx = soquet.connect_ex(addr)
      if ValorConx == 0:
        print("Porta {} aberta disponivel".format(sys.argv[3]))
      else:
        print("Porta fechada") 
  else:
    erro()
except IndexError:
  erro()
except KeyboardInterrupt:
  print("Processo fechado!")